<template>
  <div class="admin-users">
    <!-- 侧边栏 -->
    <admin-sidebar ref="sidebarRef" :class="{ collapsed: sidebarCollapsed }"/>

    <!-- 主内容区 -->
    <div class="main-content" :class="{ 'sidebar-collapsed': sidebarCollapsed }">
      <!-- 顶部导航 -->
      <admin-header
          page-title="用户管理"
          :sidebar-collapsed="sidebarCollapsed"
          @toggle-sidebar="toggleSidebar"
      />

      <!-- 内容区域 -->
      <div class="content">
        <el-card shadow="hover">
          <div class="card-header-actions">
            <el-input
                v-model="searchKeyword"
                placeholder="搜索用户名或手机号"
                prefix-icon="Search"
                class="search-input"
                show-password-on="click"
            >
              <template #append>
                <el-button type="primary" @click="handleSearch">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
              </template>
            </el-input>
            <el-select v-model="filterStatus" placeholder="用户状态" class="filter-select">
              <el-option label="全部" value=""></el-option>
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
          </div>

          <el-table
              :data="users"
              style="width: 100%"
              border
              stripe
              @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="用户ID" width="80"></el-table-column>
            <el-table-column prop="username" label="用户名"></el-table-column>
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="phone" label="手机号"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="gender" label="性别" width="80">
              <template #default="scope">
                {{ scope.row.gender || '保密' }}
              </template>
            </el-table-column>
            <el-table-column prop="age" label="年龄" width="80"></el-table-column>
            <el-table-column prop="createTime" label="注册时间">
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="180">
              <template #default="scope">
                <div class="status-container">
                  <el-tag :type="scope.row.status === '1' || scope.row.status === 1 ? 'success' : 'danger'" 
                          class="status-tag">
                    {{ scope.row.status === '1' || scope.row.status === 1 ? '启用' : '禁用' }}
                  </el-tag>
                  <el-switch
                      :model-value="scope.row.status === '1' || scope.row.status === 1"
                      @change="toggleStatus(scope.row)"
                      class="status-switch"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button type="primary" text @click="viewUserDetail(scope.row)">查看</el-button>
                <el-button type="warning" text @click="editUser(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[5, 10, 15, 20]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import AdminSidebar from '@/components/AdminSidebar.vue'
import AdminHeader from '@/components/AdminHeader.vue'
import {Search} from '@element-plus/icons-vue'
import {usersPage,updateStatus} from "@/api/Users.js";

const router = useRouter()
const sidebarCollapsed = ref(false)
const sidebarRef = ref()
//用户总记录数
const total = ref(0)
// 获取管理员信息
const adminInfo = computed(() => {
  const info = localStorage.getItem('adminInfo')
  if (info) {
    return JSON.parse(info)
  }
  // 为了开发测试，提供一个完整的默认管理员信息
  return {
    name: '管理员',
    username: 'admin', // 添加username属性，避免登录检查失败
    isSuperAdmin: true
  }
})

// 搜索和筛选
const searchKeyword = ref('')
const filterStatus = ref('')
// 用户数据
const users = ref([])
//用户的分页查询
const pageQuery = () => {
  //整合一下参数  当前页，页容量  关键词  状态
  const params = {
    "keyword": searchKeyword.value,
    "status": filterStatus.value,
    "curPage": pagination.currentPage,
    "pageSize": pagination.pageSize
  }
  usersPage(params).then(res => {
    console.log(res)
    //给用户变量赋值
    users.value=res.data.dataList
    //给当前页和页容量赋值
    pagination.currentPage = res.data.curPage
    pagination.pageSize = res.data.pageSize
    total.value = res.data.total
  })
}
// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 5
})

// 选中的用户
const selectedUsers = ref([])


// 处理菜单选择
const handleMenuSelect = (key, keyPath) => {
  activeMenu.value = key
}

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 处理退出登录
const handleLogout = () => {
  localStorage.removeItem('adminToken')
  localStorage.removeItem('adminInfo')
  ElMessage.success('退出成功')
  router.push('/admin/login')
}

// 处理个人信息
const handleProfile = () => {
  ElMessage.info('个人信息功能开发中')
}

// 格式化日期
const formatDate = (dateStr) => {
  return dateStr ? new Date(dateStr).toLocaleString('zh-CN') : ''
}

// 切换用户状态
const toggleStatus = (user) => {
  // 获取当前状态
  const currentStatus = user.status
  // 切换状态值
  const newStatus = (currentStatus === '1' || currentStatus === 1) ? '0' : '1'
  // 更新用户状态
  user.status = newStatus
  // 模拟API调用更新状态
  updateStatus({"id":user.id,"status":user.status}).then(res=>{
      if(res.code===200){
        ElMessage.success(`用户${newStatus === '1' ? '启用' : '禁用'}成功`)
      }else{
        ElMessage.error(`用户${newStatus === '1' ? '启用' : '禁用'}失败`)
      }
  })
}

// 查看用户详情
const viewUserDetail = (user) => {
  ElMessage.info(`查看用户ID: ${user.id} 的详情`)
  // 这里可以跳转到详情页或显示详情弹窗
}

// 编辑用户
const editUser = (user) => {
  ElMessage.info(`编辑用户ID: ${user.id}`)
  // 这里可以打开编辑弹窗
}

// 处理选择变更
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 处理搜索
const handleSearch = () => {
     pageQuery()
}
//当前页发生改变时的处理
const handleCurrentChange = (current) => { //current 改变之后的当前页
  pagination.currentPage = current
  pageQuery()
}

// 检查登录状态
const checkLoginStatus = () => {
  const adminToken = localStorage.getItem('adminToken')
  if (!adminToken || !adminInfo.username) {
    ElMessage.error('请先登录')
    router.push('/admin/login')
  }
}

onMounted(() => {
  // 注释掉登录验证，方便开发测试
  // checkLoginStatus()
  //调用用户分页方法
  pageQuery()
})
</script>

<style scoped>
.admin-users {
  display: flex;
  height: 100vh;
  background-color: #f0f2f5;
}

.main-content {
  flex: 1;
  margin-left: 250px;
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  transition: margin-left 0.3s ease;
}

.main-content.sidebar-collapsed {
  margin-left: 64px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    margin-left: 200px;
  }

  .main-content.sidebar-collapsed {
    margin-left: 64px;
  }
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.card-header-actions {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 150px;
}

/* 状态显示样式 */
.status-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-tag {
  flex: 1;
  text-align: center;
}

.status-switch {
  margin-left: 5px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>